// 标签切割
const labelCut = (str: string) => {
  const arrs = str.match(/<[^>]+>(?!\/>)/g);
  if (!arrs) return [];
  return arrs.filter((item) => !/<[^>]+\/>$/.test(item));
};
// 通过<></>分隔字符串=》数组
const splitStringToChunks = (str: string): string[] => {
  const chunks: string[] = [];
  let currentChunk = '';
  let insideTag = false;
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char === '<') {
      insideTag = true;
      currentChunk += char;
    } else if (char === '>') {
      insideTag = false;
      currentChunk += char;
    } else {
      currentChunk += char;
    }
    if (!insideTag || i === str.length - 1) {
      chunks.push(currentChunk);
      currentChunk = '';
    }
  }
  return chunks;
};
/**
 * @description: 文本转换数组
 * @param {string} str
 * @author: muge
 */
export const textConversionArr = (str: string): string[] => {
  const labelCutList = labelCut(str);
  const chucksList = splitStringToChunks(str);
  let startIndex: number = 0;
  const result: string[] = [];
  let lastStr = ''; //拼接的字符串
  const isCloseTagReg = /<\/[^>]*>/; //是否是闭合标签 </img>=>true  <>=>false <div/>=>false
  while (startIndex < chucksList?.length) {
    let currentIndex = startIndex;
    ++startIndex;
    const currentStr = chucksList[currentIndex];
    const index = labelCutList.indexOf(currentStr);
    if (index === -1) {
      lastStr += currentStr;
      result.push(lastStr);
      continue;
    }
    // 起始标签
    if (!/<\/[^>]+>/.test(currentStr)) {
      // 判断是否为自闭合标签，如 <img> <hr> <br>这种不规范的写法
      const nextCloseTag: string | undefined = labelCutList[index + 1];
      if (!nextCloseTag || !isCloseTagReg.test(nextCloseTag)) {
        lastStr += currentStr;
        result.push(lastStr);
        continue;
      }
      // 查找第一个闭合标签的下标
      const findArrs = chucksList.slice(currentIndex);
      const endTagIndex = findArrs.findIndex((item) => item === nextCloseTag);
      let curStr: string = '';
      for (let i = 1; i < endTagIndex; i++) {
        curStr += findArrs[i];
        const res = labelCutList[index] + curStr + nextCloseTag;
        result.push(lastStr + res);
        if (endTagIndex - 1 === i) {
          lastStr += res;
        }
      }
      startIndex = currentIndex + endTagIndex; //重置下标
      continue;
    }
  }
  return result;
};
